<template>
    <div class="chat-container">
      <!-- 左侧历史记录 -->
      <div class="history-sidebar custom-scrollbar">
        <div class="sidebar-header">
          <h2>历史记录</h2>
          <el-button
            type="primary"
            icon="Plus"
            circle
            @click="createNewSession"
          ></el-button>
        </div>
        <ul v-infinite-scroll="handleScroll">
          <li
            v-for="(session, index) in sessions"
            :key="index"
            @click="loadDialogue(session.id)"
            :class="{ active: session.id === activeSessionId }"
          >
            <div class="session-item">
              <span v-if="!session.isEditing">{{
                truncatedSessionName(session.session_name)
              }}</span>
              <input
                v-else
                :value="session.session_name"
                @input="updateSessionName(session, $event.target.value)"
                @click.stop
                class="truncated-input"
              />
              <div class="session-actions">
                <el-button
                  v-if="!session.isEditing"
                  type="text"
                  @click.stop="toggleEditSession(session)"
                  >编辑</el-button
                >
                <el-button
                  v-if="session.isEditing"
                  :icon="Select"
                  type="plain"
                  class="red-icon"
                  style="color: green"
                  @click.stop="saveSessionName(session)"
                ></el-button>
                <el-button
                  type="text"
                  style="color: red"
                  @click.stop="deleteSession(session.id)"
                  v-if="!session.isEditing"
                  >删除</el-button
                >
                <el-button
                  v-if="session.isEditing"
                  :icon="CloseBold"
                  type="plain"
                  class="red-icon"
                  style="color: red"
                  @click.stop="toggleEditSession(session)"
                ></el-button>
              </div>
            </div>
          </li>
        </ul>
      </div>
  
      <!-- 右侧聊天窗口 -->
      <div class="chat-window">
        <div class="messages custom-scrollbar" ref="messagesContainer">
          <!-- 消息列表 -->
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message', message.sender]"
          >
            <div class="message-content">
              {{ message.content }}
            </div>
          </div>
  
          <!-- 加载状态 -->
          <div v-if="isLoading" class="message bot">
            <div class="message-content">
              <!-- <div class="loading">加载中...</div> -->
              <el-button loading class="transparent-button">Loading</el-button>
            </div>
          </div>
        </div>
  
        <!-- 输入区域 -->
        <div class="input-area">
          <input
            v-model="query"
            placeholder="输入问题"
            @keyup.enter="sendQuery"
          />
          <button @click="sendQuery">发送</button>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { EditPen, Select, CloseBold } from '@element-plus/icons-vue'
  import { ElLoading } from 'element-plus'
  import { fa, pa } from 'element-plus/es/locale/index.mjs'
  import { onMounted, ref, nextTick } from 'vue'
  import {
    ChatCreateSession,
    ChatSessionList,
    ChatDialogueList,
    ChatAnswer,
    ChatSaveSession,
    ChatDeleteSession
  } from '~/api/manager'
  // const onSubmit = () => {
  //     ChatCreateSession({session_name: '新建会话'}).then((res)=>{
  
  //     })
  // }
  
  const query = ref('') // 输入的问题
  const sessions = ref([]) // 历史会话列表
  const activeSessionId = ref(null)
  const messages = ref([])
  const isLoading = ref(false)
  const messagesContainer = ref(null)
  // 历史会话的记录
  const sessionListCount = ref(0)
  const sessionPage = ref(1)
  const sessionLimit = ref(12)
  // 聊天历史的记录
  const dialogueListCount = ref(0)
  const dialoguePage = ref(1)
  
  // 新建会话
  const createNewSession = () => {
    ChatCreateSession({ session_name: '新建会话' }).then((res) => {
      loadSessions(sessionPage.value)
    })
  }
  // 编辑会话名称
  // 限制名称的展示字数
  const truncatedSessionName = (name) => {
    console.log(name)
  
    const maxLength = 4 // 最大显示字符数
    return name.length > maxLength ? name.slice(0, maxLength) + '...' : name
  }
  
  const updateSessionName = (session, newName) => {
    session.session_name = newName // 更新实际的值
  }
  // 修改状态位
  const toggleEditSession = (session) => {
    session.isEditing = !session.isEditing
  }
  // 修改会话名称
  const saveSessionName = (session) => {
    const loadingInstance = ElLoading.service({ fullscreen: true })
    ChatSaveSession({
      session_id: session.id,
      session_name: session.session_name
    }).then((res) => {
      console.log(res)
      toggleEditSession(session)
      loadingInstance.close()
    })
  }
  // 删除会话
  const deleteSession = (sessionId) => {
    ChatDeleteSession(sessionId).then((res) => {
      // 从历史记录列表中移除会话
      sessions.value = sessions.value.filter(
        (session) => session.id !== sessionId
      )
      // 如果删除的是当前选中的会话，清空消息列表
      if (activeSessionId.value === sessionId) {
        messages.value = []
        activeSessionId.value = null
        // 如果还存在对话历史就选中第一条
        if (sessions.value.length > 0) {
          loadDialogue(sessions.value[0].id)
        }
      }
    })
  }
  
  // 获取会话列表
  const loadSessions = (page) => {
    const loadingInstance = ElLoading.service({ fullscreen: true })
    ChatSessionList({ page: page, limit: sessionLimit.value }).then((res) => {
      sessions.value = res.data
      sessionListCount.value = res.count
      // 默认选中第一个会话
      if (sessions.value.length > 0) {
        loadDialogue(sessions.value[0].id)
      }
      loadingInstance.close()
    })
  }
  // 往下滚动加载会话列表
  const handleScroll = () => {
    if (
      messagesContainer.value.scrollTop + messagesContainer.value.clientHeight >=
      messagesContainer.value.scrollHeight
    ) {
      // 滚动到底部，加载下一页
      if (sessionPage.value * sessionLimit.value < sessionListCount.value) {
        const loadingInstance = ElLoading.service({ fullscreen: true })
        sessionPage.value++
        ChatSessionList({ page: sessionPage.value, limit: 11 }).then((res) => {
          sessionListCount.value = res.count
          sessions.value = sessions.value.concat(res.data)
          loadingInstance.close()
        })
      }
    }
  }
  
  // 获取指定会话列表中的消息列表
  const loadDialogue = (sessionId) => {
    const loadingInstance = ElLoading.service({ fullscreen: true })
    activeSessionId.value = sessionId
    ChatDialogueList({ session_id: sessionId, page: dialoguePage.value }).then(
      (res) => {
        dialogueListCount.value = ref.count
        // 提取对话数据
        const dialogues = res.data
        messages.value = dialogues
          .map((dialogue) => [
            { sender: 'user', content: dialogue.query },
            { sender: 'bot', content: dialogue.answer }
          ])
          .flat() // 将嵌套数组展平
        loadingInstance.close()
        scrollToBottom()
      }
    )
  }
  
  // 发送问题
  const sendQuery = () => {
    if (query.value.trim() === '') return
    messages.value.push({ sender: 'user', content: query.value })
    const user_query = query.value
    query.value = ''
    isLoading.value = true
    scrollToBottom()
    ChatAnswer({ query: user_query, session_id: activeSessionId.value }).then(
      (res) => {
        messages.value.push({ sender: 'bot', content: res.data.answer })
        if (res.data.session_id !== activeSessionId.value) {
          // 如果会话id不一致，则更新会话列表
          loadSessions(1)
        }
        activeSessionId.value = res.data.session_id
        isLoading.value = false
        scrollToBottom()
      }
    )
  }
  
  // 滚动到底部
  const scrollToBottom = () => {
    nextTick(() => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
      }
    })
  }
  
  onMounted(() => {
    loadSessions(sessionPage.value)
    scrollToBottom()
  })
  </script>
  
  <style scoped>
  .transparent-button {
    background-color: transparent !important;
    border-color: transparent !important;
  }
  
  /* 如果需要，可以添加鼠标悬停时的效果 */
  .transparent-button:hover {
    background-color: transparent !important;
    border-color: transparent !important;
  }
  
  /* 如果需要，可以添加点击时的效果 */
  .transparent-button:active {
    background-color: transparent !important;
    border-color: transparent !important;
  }
  /* 确保 html 和 body 占满整个屏幕高度，并禁止全局滚动 */
  html,
  body {
    height: 100%;
    margin: 0;
    padding: 0;
    overflow: hidden; /* 禁止全局滚动 */
  }
  
  .chat-container {
    display: flex;
    /* height: calc(100vh - 20px); */
    height: 780px;
    background-color: #f5f5f5;
    overflow: hidden; /* 禁止容器滚动 */
  }
  
  .history-sidebar {
    height: 100%;
    width: 250px;
    background-color: #ffffff; /* 白色背景 */
    border: 1px solid #dbd9d9; /* 黑色边框，宽度为1px，样式为实线 */
    border-radius: 8px; /* 圆角边框，半径可以根据需要调整 */
    padding: 20px;
    overflow-y: auto; /* 允许侧边栏内部滚动 */
  }
  
  .history-sidebar h2 {
    margin-bottom: 20px;
  }
  
  .history-sidebar ul {
    list-style: none;
    padding: 0;
  }
  
  .history-sidebar li {
    padding: 10px;
    cursor: pointer;
    border-radius: 5px; /* 灰色圆角边框 */
    border: 1px solid #e7e2e2; /* 灰色边框 */
    border-radius: 5px;
    margin-bottom: 5px;
    color: black; /* 确保字体颜色为白色 */
  }
  
  .history-sidebar li:hover {
    background-color: #75afe9;
  }
  
  .history-sidebar li.active {
    background-color: #c4ecec;
  }
  
  .chat-window {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: white;
    overflow: hidden; /* 禁止聊天窗口滚动 */
  }
  
  .messages {
    flex: 1;
    padding: 20px;
    overflow-y: auto; /* 允许消息区域内部滚动 */
    overflow-x: hidden; /* 禁止水平滚动 */
  }
  
  .message {
    margin-bottom: 15px;
    display: flex;
  }
  .sidebar-header {
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: space-between; /* 标题和按钮分开 */
    margin-bottom: 20px;
  }
  
  .add-session-btn {
    background: none;
    border: none;
    color: white;
    font-size: 24px;
    cursor: pointer;
    padding: 0 10px;
  }
  
  .add-session-btn:hover {
    color: #1abc9c; /* 鼠标悬停时改变颜色 */
  }
  .message.user {
    justify-content: flex-end;
  }
  
  .message.bot {
    justify-content: flex-start;
  }
  
  .message-content {
    max-width: 70%;
    padding: 10px;
    border-radius: 10px;
  }
  
  .message.user .message-content {
    background-color: #1abc9c;
    color: white;
  }
  
  .message.bot .message-content {
    background-color: #ecf0f1;
    color: #2c3e50;
  }
  
  .loading {
    color: #666;
    font-style: italic;
  }
  
  .input-area {
    display: flex;
    padding: 20px;
    background-color: #f5f5f5;
    border-top: 1px solid #ddd;
  }
  
  .input-area input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
    margin-right: 10px;
  }
  
  .input-area button {
    padding: 10px 20px;
    background-color: #1abc9c;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
  }
  
  .input-area button:hover {
    background-color: #16a085;
  }
  .session-item {
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: space-between; /* 名称和按钮分开 */
    width: 100%; /* 占满父容器宽度 */
  }
  .session-actions {
    display: flex;
    gap: 5px; /* 按钮之间的间距 */
    justify-content: flex-end;
    align-items: center;
  }
  .session-actions .el-button {
    margin-left: 5px; /* 调整按钮之间的间距 */
  }
  
  .edit-btn,
  .delete-btn {
    background: none;
    border: none;
    color: white;
    font-size: 16px;
    cursor: pointer;
    padding: 0;
  }
  
  .edit-btn:hover {
    color: #1abc9c; /* 鼠标悬停时改变颜色 */
  }
  
  .delete-btn:hover {
    color: #e74c3c; /* 鼠标悬停时改变颜色 */
  }
  
  li input {
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 5px;
    width: 60%; /* 输入框宽度 */
  }
  /* 自定义滚动条样式 */
  .custom-scrollbar::-webkit-scrollbar {
    width: 8px; /* 滚动条宽度 */
  }
  
  .custom-scrollbar::-webkit-scrollbar-track {
    background: transparent; /* 轨道背景，默认透明 */
  }
  
  .custom-scrollbar::-webkit-scrollbar-thumb {
    background: transparent; /* 滚动条滑块，默认透明 */
    border-radius: 4px; /* 滑块圆角 */
  }
  
  .custom-scrollbar:hover::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.1); /* 滚动时滑块颜色 */
  }
  
  .el-button--plain.red-icon {
    background-color: transparent;
    border: none;
  }
  .truncated-input {
    width: 80px; /* 根据需要调整宽度 */
    white-space: nowrap; /* 禁止换行 */
    overflow: hidden; /* 隐藏超出部分 */
    text-overflow: ellipsis; /* 超出部分显示省略号 */
  }
  </style>
  